namespace imitateMacQQ.WebApi.Repository.Redis;

using StackExchange.Redis;
using System;
using System.Collections.Concurrent;

public class RedisHelper : IDisposable
{
    //连接字符串
    private readonly string _connectionString;

    //实例名称
    private readonly string _instanceName;

    //默认数据库
    private readonly int _defaultDb;
    private readonly ConcurrentDictionary<string, ConnectionMultiplexer> _connections;

    public RedisHelper(string connectionString, string instanceName, int defaultDb = 0)
    {
        _connectionString = connectionString;
        _instanceName = instanceName;
        _defaultDb = defaultDb;
        _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
        GetDatabase().Execute("FlUSHDb");//初始化刷新
    }

    /// <summary>
    /// 获取ConnectionMultiplexer
    /// </summary>
    /// <returns></returns>
    private ConnectionMultiplexer GetConnect()
    {
        return _connections.GetOrAdd(_instanceName,ConnectionMultiplexer.Connect(_connectionString));
    }


    public IDatabase GetDatabase()
    {
        return GetConnect().GetDatabase(_defaultDb);
    }

    public IServer GetServer(int endPointsIndex = 0)
    {
        var confOption = ConfigurationOptions.Parse(_connectionString);
        return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
    }

    public ISubscriber GetSubscriber()
    {
        return GetConnect().GetSubscriber();
    }

    public void Dispose()
    {
        // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
        if (_connections is { IsEmpty: false })
        {
            foreach (var item in _connections.Values)
            {
                item.Close();
            }
        }
    }
}